﻿using SmallJob.Model;
using SmallJob.Services.Code;
using SmallJob.Services.Interfaces;
using SmallShop.Services.Code;
using SmallShop.Services.Implements;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FrontEnd.Controllers
{
    public class FileController : Controller
    {
        private readonly IUserService _UserService;
        private readonly IOrderService _OrderService;

        public FileController(IUserService UserService, IOrderService OrderService)
        {
            _UserService = UserService;
            _OrderService = OrderService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult FormUpload()
        {
            ViewData["issuccess"] = TempData["issuccess"];
            ViewData["error"] = TempData["error"];
            ViewData["size"] = TempData["size"];
            return View();
        }

        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            if (!User.Identity.IsAuthenticated) return RedirectToAction("Index", "Home");
            var user = UtilityService.GetLoginUser(_UserService, User);
            if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                fileName = UploadHelper.GetNamePlusDatetime(fileName, true);
                var path = Path.Combine(UploadHelper.GetPathSaveFile(user.ID), fileName);
                if (file.ContentLength > (1024 * 1024 * 100))
                {
                    TempData["issuccess"] = false;
                    TempData["error"] = "Độ lớn file vượt quá cho phép.";
                    TempData["size"] = file.ContentLength;
                    return RedirectToAction("FormUpload", "File");
                }
                TempData["issuccess"] = true;
                TempData["size"] = file.ContentLength;
                file.SaveAs(path);
            }
            return RedirectToAction("FormUpload", "File");
        }

        [HttpGet]
        public ActionResult Download(string id, string filename, string code)
        {
            //var context = HttpContext;
            if (!User.Identity.IsAuthenticated)
            {
                //Response.StatusCode = 404;
                return RedirectToAction("Error404", "Error");
            }
            if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(filename) || string.IsNullOrWhiteSpace(code))
            {
                return RedirectToAction("Error404", "Error");
            }
            int intownerid = 0;
            int intorderid = 0;
            try
            {
                intorderid = Convert.ToInt32(id);
            }
            catch (Exception) { return RedirectToAction("Error404", "Error"); }
            var user = UtilityService.GetLoginUser(_UserService, User);
            var order = _OrderService.GetById(intorderid);
            if (order == null || (OrderHelper.GetWorkerID(order) != user.ID && OrderHelper.GetPayerID(order) != user.ID) || order.PaymentStatus == (int)EPaymentStatus.No_Payment)
            {
                return RedirectToAction("Error404", "Error");
            }
            intownerid = OrderHelper.GetWorkerID(order);
            if (intownerid != user.ID)
            {
                //Response.StatusCode = 404;
                var test = HttpUtility.UrlEncode(UserUtility.HashCode(intownerid + filename + user.ID));
                var temp = UserUtility.HashCode(intownerid + filename + user.ID);
                if (!code.Equals(UserUtility.HashCode(intownerid + filename + user.ID + intorderid)))
                {
                    return RedirectToAction("Error404", "Error");
                }
            }
            var filePath = Path.Combine(UploadHelper.GetPathSaveFile(intownerid), filename);

            if (System.IO.File.Exists(filePath))
            {
                //context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
                //context.Response.ContentType = "application/octet-stream";
                //context.Response.ClearContent();
                //context.Response.WriteFile(filePath);
                return File(filePath, "application/octet-stream", filename);
            }
            else
            {
                //Response.StatusCode = 404;
                return RedirectToAction("Error404", "Error");
            }
        }

    }
}